import pyautogui
import time


def wait_and_locate(image_path, timeout=30, confidence=0.8):
    """
    循环等待定位图片，直到找到或超时
    """
    start_time = time.time()
    while time.time() - start_time < timeout:
        location = pyautogui.locateCenterOnScreen(image_path, confidence=confidence)
        if location is not None:
            return location
        print(f"等待 {image_path} 出现...（剩余 {int(timeout - (time.time() - start_time))} 秒）")
        time.sleep(1)
    print(f"超时未找到 {image_path}，请检查图片或界面状态")
    return None


def wait_and_double_click(image_path, timeout=30, confidence=0.8):
    """
    等待并双击图片，带超时和重试
    """
    location = wait_and_locate(image_path, timeout, confidence)
    if location:
        pyautogui.doubleClick(location)
        print(f"成功双击 {image_path}")


def wait_and_click_with_offset(image_path, x_offset=0, y_offset=0, timeout=30, confidence=0.8):
    """
    等待并点击图片（带偏移量），带超时和重试
    """
    location = wait_and_locate(image_path, timeout, confidence)
    if location:
        x, y = location
        new_x = x + x_offset
        new_y = y + y_offset
        pyautogui.click(new_x, new_y)
        print(f"成功点击 {image_path} 并偏移 ({x_offset}, {y_offset})")


def click_until_disappear(image_path, x_offset=0, y_offset=0, check_interval=1, max_attempts=50):
    """
    循环点击图片直到消失（防止界面卡顿）
    """
    attempts = 0
    while attempts < max_attempts:
        location = pyautogui.locateCenterOnScreen(image_path, confidence=0.8)
        if not location:
            break
        x, y = location
        new_x = x + x_offset
        new_y = y + y_offset
        pyautogui.click(new_x, new_y)
        print(f"点击 {image_path} 并偏移 ({x_offset}, {y_offset})")
        time.sleep(check_interval)
        attempts += 1
    print(f"{image_path} 已消失或达到最大尝试次数")


def main():
    # 全局参数设置
    dpi = 96
    default_timeout = 30  # 图片等待超时时间（秒）
    confidence = 0.8  # 图片匹配置信度（0.1-1.0）

    # 计算常用偏移量（厘米转像素）
    def cm_to_pixel(cm):
        return int((cm / 2.54) * dpi)

    offset_2cm = cm_to_pixel(2)
    offset_1_6cm = cm_to_pixel(1.6)
    offset_14cm = cm_to_pixel(14)
    offset_3_5cm = cm_to_pixel(3.5)

    # 1. 双击 mhxy.png（带循环等待）
    wait_and_double_click(
        image_path=r"G:\zdh\yolo2\png\mhxy.png",
        timeout=default_timeout
    )
    time.sleep(4)

    # 2. 点击 dl.png（带循环等待和偏移量）
    wait_and_click_with_offset(
        image_path=r"G:\zdh\yolo2\png\dl.png",
        x_offset=-offset_2cm,
        timeout=default_timeout,
        confidence=confidence
    )
    time.sleep(5)

    # 3. 点击 xyb.png 直到消失（用户自定义偏移量）
    xyb_x_offset = 0
    xyb_y_offset = 10
    click_until_disappear(
        image_path=r"G:\zdh\yolo2\png\xyb.png",
        x_offset=xyb_x_offset,
        y_offset=xyb_y_offset
    )
    time.sleep(1)

    # 4. 按下回车键（防止界面卡顿）
    pyautogui.press('enter')
    time.sleep(6)

    # 5. 点击 ptdl.png（带向下偏移）
    wait_and_click_with_offset(
        image_path=r"G:\zdh\yolo2\png\ptdl.png",
        y_offset=offset_3_5cm,
        timeout=default_timeout,
        confidence=confidence
    )

    # 6. 输入账号密码（带大小写处理）
    input_str = 'poiuyT54'
    for char in input_str:
        if char.isupper():
            pyautogui.keyDown('shift')
            pyautogui.press(char.lower())
            pyautogui.keyUp('shift')
        else:
            pyautogui.press(char)
        time.sleep(0.1)
    pyautogui.press('enter')


if __name__ == "__main__":
    main()